package top.infopub.mgr.bpa.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.infopub.dto.bpa.BpaPublicProInfoDto;
import top.infopub.dto.bpa.ProjectBudgetDto;
import top.infopub.enums.bpa.BpaProcessDetailTypeEnum;
import top.infopub.enums.mkt.ProProcesssStatusEnum;
import top.infopub.enums.mkt.ProjectFileTypeEnum;
import top.infopub.mgr.bpa.dao.BpaProjectBudgetDao;
import top.infopub.mgr.bpa.dao.BpaProjectBudgetDetailDao;
import top.infopub.mgr.bpa.jsonVo.BpaProjectBudgetJsonVo;
import top.infopub.mgr.bpa.service.BpaProcessManageService;
import top.infopub.mgr.bpa.service.BpaProjectBudgetService;
import top.infopub.mgr.bpa.vo.BpaProjectBudget;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.service.OAFlowService;
import top.infopub.mgr.mkt.dao.ProjectAttachmentDao;
import top.infopub.mgr.mkt.service.ProjectInfoService;
import top.infopub.mgr.mkt.service.SetupProService;
import top.infopub.mgr.util.FileAttrUtils;
import top.infopub.model.bpa.ProjectBudget;
import top.infopub.model.bpa.ProjectBudgetDetail;
import top.infopub.model.mkt.ProjectAttachment;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.util.IdFactory;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by wurz on 2021/6/18.
 */
@Service
public class BpaProjectBudgetServiceImpl implements BpaProjectBudgetService {
    @Resource
    private BpaProjectBudgetDao bpaProjectBudgetDao;

    @Autowired
    private BpaProjectBudgetDetailDao bpaProjectBudgetDetailDao;

    @Resource
    private ProjectAttachmentDao projectAttachmentDao;

    @Autowired
    private ProjectInfoService projectInfoService;

    @Autowired
    private OAFlowService oaFlowService;

    @Autowired
    private SetupProService setupProService;

    @Autowired
    private BpaProcessManageService bpaProcessManageService;

    @Override
    public int deleteByPrimaryKey(String id) {
        return bpaProjectBudgetDao.deleteByPrimaryKey(id);
    }

    @Override
    public ProjectBudget selectOne(String id) {
        return bpaProjectBudgetDao.selectOne(id);
    }

    @Override
    public int selectCount(BpaProjectBudget budget) {
        return bpaProjectBudgetDao.selectCount(budget);
    }

    @Override
    public Page<BpaProjectBudget> selectList(Page<BpaProjectBudget> page, BpaProjectBudget bpaPrimarySure) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        //先查项目名--》查出项目编号
        return bpaProjectBudgetDao.selectList(bpaPrimarySure);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public RspVo edit(BpaProjectBudgetJsonVo proBudgetJson, Integer submitType, AuthorizationVO vo) {
        String id = proBudgetJson.getInfo().getId();
        ProjectBudget tmpProBudget = new ProjectBudget();
        ProjectBudget proBudget = new ProjectBudget();
        BeanUtils.copyProperties(proBudgetJson.getInfo(), proBudget);
        proBudget.setUptBy(vo.getId());
        proBudget.setUptTime(new Date());
        if (StringUtils.isNotBlank(id)) {
            //校验数据是否存在
            tmpProBudget = this.selectOne(id);
            if (tmpProBudget == null) return RspVo.getFailureResponse(400, "项目预结算数据不存在");
            //判断审批状态
            if (StringUtils.isNotBlank(tmpProBudget.getProcessStatus())
                    && (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), tmpProBudget.getProcessStatus())
                    || StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS9.getCode(), tmpProBudget.getProcessStatus()))) {
                return RspVo.getFailureResponse(400, "审批状态不正确，操作失败");
            }
            //更新
            bpaProjectBudgetDao.updateByPrimaryKey(proBudget);
        } else {
            proBudget.setCodes(IdFactory.getUUIDUpper());
            proBudget.setAddBy(vo.getId());
            proBudget.setAddTime(new Date());
            bpaProjectBudgetDao.insert(proBudget);
        }
        //更新详细列表
        List<ProjectBudgetDetail> detailList = proBudgetJson.getDetailList();
        bpaProjectBudgetDetailDao.deleteByBudgetSguid(proBudget.getId());
        if (detailList != null && detailList.size() > 0) {
            int index = 1;
            for (ProjectBudgetDetail pbd : detailList) {
                if (pbd == null) continue;
                pbd.setAddBy(vo.getId());
                pbd.setAddTime(new Date());
                pbd.setBudgetSguid(proBudget.getId());
                pbd.setSeq(index);
                bpaProjectBudgetDetailDao.insert(pbd);
                index++;
            }
        }

        //更新附件表-MKT_PROJECT_ATTACHMENT--该处ID映射好
        List<ProjectAttachment> attachmentList = new ArrayList<>();
        if(proBudgetJson.getFileAtt()!=null){
            String[] fileAtt = proBudgetJson.getFileAtt();
            for (String file : fileAtt) {
                ProjectAttachment attachment = FileAttrUtils.createProjectFileAtta(proBudget.getId(), file);
                attachmentList.add(attachment);
            }
        }
        //更新附件信息--根据不同类型的ProjectFileTypeEnum处理附件信息
        projectAttachmentDao.deleteByWhere(id, ProjectFileTypeEnum.FILE_TYPE126.getCode(), null);
        if (attachmentList != null && attachmentList.size() > 0) {
            projectAttachmentDao.insertBatch(attachmentList);
        }
        if (submitType == 1) {
            //处理OA待办，主表里的OA_ID
            if (StringUtils.isNotBlank(tmpProBudget.getOaId())) {
                oaFlowService.finishOA(tmpProBudget.getOaId());
            }
            String detailJson = JSON.toJSONString(queryDetailById(proBudget.getId()));
            bpaProcessManageService.sendProcess(BpaProcessDetailTypeEnum.PRO_NODE_TYPE23, detailJson, proBudget.getId(), proBudget.getProCode(), vo);
        }
        return RspVo.getSuccessResponse();
    }

    @Override
    public BpaProjectBudgetJsonVo queryDetailById(String id) {
        BpaProjectBudgetJsonVo proBudgetJson = new BpaProjectBudgetJsonVo();
        if (StringUtils.isNotBlank(id)) {
            //id存在(详情)查询详情信息
            ProjectBudgetDto proBudgetDto = new ProjectBudgetDto();
            ProjectBudget proBudget = bpaProjectBudgetDao.selectOne(id);
            BeanUtils.copyProperties(proBudget, proBudgetDto);
            //查询项目基础信息
            BpaPublicProInfoDto proInfoDto = projectInfoService.queryBpaProInfoByProCode(proBudget.getProCode());
            BeanUtils.copyProperties(proInfoDto, proBudgetDto);
            proBudgetJson.setInfo(proBudgetDto);
            //详情信息
            List<ProjectBudgetDetail> detailList = bpaProjectBudgetDetailDao.queryByBudgetSguid(id);
            proBudgetJson.setDetailList(detailList);
            //文件列表
            List<ProjectAttachment> projectAttaList = projectAttachmentDao.queryByWhere(id, ProjectFileTypeEnum.FILE_TYPE126.getCode(), null);
            proBudgetJson.setFileAtt(setupProService.fileAttaListToArray(projectAttaList));
        } else {
            //查询项目列表
            proBudgetJson.setProInfoList(setupProService.getProjectBudgetMktList());
        }
        return proBudgetJson;
    }

    @Override
    public BpaProjectBudgetJsonVo queryProInfoByProCode(String proCode) {
        BpaProjectBudgetJsonVo proBudgetJson = new BpaProjectBudgetJsonVo();
        ProjectBudgetDto proBudgetDto = new ProjectBudgetDto();
        //查询项目基础信息
        BpaPublicProInfoDto proInfoDto = projectInfoService.queryBpaProInfoByProCode(proCode);
        BeanUtils.copyProperties(proInfoDto, proBudgetDto);
        proBudgetJson.setInfo(proBudgetDto);
        return proBudgetJson;
    }
}
